/**
 * name: index.js
 * works：首页脚本
 */


//页面 mainLayer 大小自适应
var autoPageSize = function (column) {
	var bodyH = $(window).height(),
		bodyW = $(window).width(),
		topH = $(".mainLayer .sidebar .top").outerHeight(),
		main = $(".mainLayer"),
		sidebar = $(".mainLayer .sidebar"),
		table = $(".mainLayer .table"),
		easyTree = $(".mainLayer .sidebar .easyTree"),
		item = $(".mainLayer .item"),
		mainH = bodyH - 100,
		mainW = bodyW;

	//设置mainLayer高、宽
	main.css({"height": mainH, "width": mainW});

	//设置easyTree高
	easyTree.css("height", mainH - topH - 30);

	switch (column){
		//浏览视图
		case 2:
			var sidebarW = bodyW * 0.25,
				tableW = bodyW * 0.75;

			item.hide();
			sidebar.css("width", sidebarW);
			table.css("width", tableW);
			break;

		//默认视图
		case 3:
			var sidebarW = bodyW * 0.25,
				tableW = bodyW * 0.4,
				itemW = bodyW * 0.35;

			item.show();
			sidebar.css("width", sidebarW);
			table.css("width", tableW);
			item.css("width", itemW);
			break;
	}

}

//顶部菜单事件
var topMenuFn = function () {

	//打开SCL
	$(".topMenu .open .file").bind("change", function(){
		var formData = new FormData($("#fileUplaod")[0]);
		var avaTableList = $("#dialog-available").find("#avaTableList");
		$.ajax({
			url: '/iec61850/openSCL',
			type: 'POST',
			data: formData,
			async: false,
			cache: false,
			contentType: false,
			processData: false,
			success: function (d) {
				var item = d.data;
				if (d.success == true) {
					//渲染表单数据
					avaTableList.empty();
					$("#dialog-available").find("#selectAll").attr("checked", false);
					$("#avaTableListTmpl").tmpl(item).appendTo(avaTableList);

					function chenkboxClick(){
						var $checkbox =  avaTableList.find("input[type=checkbox]");
						//表单全选
						$("#dialog-available").find("#selectAll").on("click", function() {
							avaTableList.find("input[type=checkbox]").attr("checked", this.checked);
						});
						//表单单选
						$checkbox.on("click", function() {
							$("#dialog-available").find("#selectAll").attr("checked", $checkbox.length == avaTableList.find("input[type=checkbox]:checked").length ? true : false);
						});
					}
					chenkboxClick();

					//设置弹窗
					$("#dialog-available").dialog({
						resizable: false,
						width:460,
						height:260,
						modal: true,
						buttons: {
							"OK": function() {
								if($("#avaTableList :checked").length > 0){
									//遍历表单并渲染设备列表数据
									var objArray = [];

									$("#avaTableList :checked").each(function(i) {
										var name = $(this).val(),
											ip = $(this).attr("data-ip"),
											filePath = $(this).attr("data-path"),
											port = $(this).attr("data-port"),
											data = {"name": name, "ip": ip, "path": filePath, "port": port};

										//obj[i] = JSON.stringify(data);
										objArray.push(data);
									});
									//console.log(obj);
									var dataParm = JSON.stringify(objArray);
									$.ajax({
										url: '/iec61850/importSCL',
										type: 'POST',
										data: dataParm,
										dataType: "json",
										contentType: "application/json",
										success: function (d){
											var item = d.data;
											if(d.success == true){
												for(var i = 0; i < item.length; i++) {
													$("#deviceList").prepend("<li><a href='javaScript:;' data-type='byScl' data-ip='" + item[i].ip + "' data-path='" + item[i].path + "' data-online='" + item[i].online +"' data-port='" + item[i].port + "'>" + item[i].name + "</a></li>");
												}
												$.gritter.add({
													title: 'success',
													text: '打开SCL成功，在设备列表中选择对应设备！',
													position: 'bottom-right',
													class_name: 'gritter-success'
												});
												$("#dialog-available").dialog("close");
											} else {
												$.gritter.add({
													title: 'error',
													text: d.msg,
													class_name: 'bottom-right'
												});
											}
										},
										error: function (error){
											$.gritter.add({
												title: 'error',
												text: 'importSCL data error.',
												position: 'bottom-right',
												class_name: 'gritter-success'
											});
										}
									});
								} else {
									$.gritter.add({
										title: 'error',
										text: 'Option is null.',
										position: 'bottom-right',
										class_name: 'gritter-success'
									});
								}
							},
							"Cancel": function() {
								$('#fileUplaod input[type="file"]').val('');
								$(this).dialog("close");
							}
						}
					});
				} else {
					$.gritter.add({
						title: 'error',
						text: d.msg,
						class_name: 'bottom-right'
					});
				}
			},
			error: function (error) {
				$.gritter.add({
					title: 'error',
					text: 'openSCL data error！',
					class_name: 'bottom-right'
				});
			}
		});
	});

	//查找IED
	$(".topMenu .search").bind("click", function(){
		var tBtn = $("#dialog-discover .toggleBtn"),
			tLayer = $("#dialog-discover .toggleLayer"),
			disBtn = $("#dialog-discover #disableBtn"),
			disInput_1 = $("#dialog-discover #ipProxy"),
			disInput_2 = $("#dialog-discover #pPort");
		//设置弹窗
		$("#dialog-discover").dialog({
			resizable: false,
			width: 660,
			height: 600,
			modal: true,
			buttons: {
				"Save": function() {
					var dataParm = $("#discoverForm").serialize();
					//保存数据
					$.ajax({
						type: "POST",
						url: "/iec61850/discoverIED",
						data: dataParm,
						success: function (d) {
							var item = d.data;
							if(d.success == true){
								$("#deviceList").prepend("<li><a href='javaScript:;' data-type='discover' data-ip='" + item.ip + "' data-path='' data-online='"+ item.online +"'>" + item.ip + "</a></li>");
								$.gritter.add({
									title: 'success',
									text: '查找IED成功，在设备列表中选择对应设备！',
									position: 'bottom-right',
									class_name: 'gritter-success'
								});
								$("#dialog-discover").dialog("close");
							} else {
								$.gritter.add({
									title: 'error',
									text: d.msg,
									class_name: 'bottom-right'
								});
							}
						},
						error: function(error) {
							$.gritter.add({
								title: 'error',
								text: 'discoverIED data error！',
								class_name: 'bottom-right'
							});
						}
					});
				},
				"Cancel": function() {
					$(this).dialog("close");
				}
			}
		});

		//隐藏/显示
		toggleFn(tBtn, tLayer);

		//IP输入框
		$("#discoverForm .ip").ipaddress();

		//设置input属性
		disableBtnFn(disBtn, disInput_1, disInput_2);
	});

	//在线
	$(".topMenu .online").bind("click", function(){
		var name = $(".sidebar .iedsBtn em").text(),
			ip = $(".sidebar .ip").text(),
			online = $(".sidebar .ip").attr("data-online");
			port = $(".sidebar .ip").attr("data-port");

		if(name != "选择设备"){
			$.ajax({
				type: "POST",
				url: "/iec61850/onlineIED",
				data: {"ip": ip, "online": online, "port": port},
				dataType: "json",
				success: function (d) {
					var item = d.data;
					var msg = "设备已离线！";
					if(d.success){
						$("#deviceList").empty();
						$(".sidebar .ip").attr("data-online", item.online);
						deviceListAjax();
						if(item.online == true){
							msg = "设备已在线！";
						}
						$.gritter.add({
							title: 'success',
							text: msg,
							class_name: 'bottom-right'
						});
					} else {
						$.gritter.add({
							title: 'error',
							text: d.msg,
							class_name: 'bottom-right'
						});
					}
				},
				error: function(error) {
					$.gritter.add({
						title: 'error',
						text: 'onlineIED data error！',
						class_name: 'bottom-right'
					});
				}
			});
		} else {
			$.gritter.add({
				title: 'error',
				text: '在设备列表中选择对应设备！',
				class_name: 'bottom-right'
			});
		}
	});

	//关闭IED
	$(".topMenu .close").bind("click", function(){
		var name = $(".sidebar .iedsBtn em").text(),
			ip = $(".sidebar .ip").text(),
			online = $(".sidebar .ip").attr("data-online");

		if(name != "选择设备"){
			if(online = "true"){
				//设置弹窗
				$("#dialog-text").dialog({
					resizable: false,
					width: 400,
					modal: true,
					buttons: {
						"Ok": function() {
							//关闭对应IP设备
							closeIEDAjax(ip, online);
						},
						"No": function() {
							$(this).dialog("close");
						}
					}
				});
			} else {
				closeIEDAjax(ip, online);
			}
		} else {
			$.gritter.add({
				title: 'error',
				text: '在设备列表中选择对应设备！',
				class_name: 'bottom-right'
			});
		}
	});

	//设置IED
	$(".topMenu .set").bind("click", function(){
		var tBtn = $("#dialog-scout .toggleBtn"),
			tLayer = $("#dialog-scout .toggleLayer"),
			disBtn = $("#dialog-scout #disableBtn"),
			disInput_1 = $("#dialog-scout #ipProxy"),
			disInput_2 = $("#dialog-scout #pPort"),
			name = $(".sidebar .iedsBtn em").text(),
			ip = $(".sidebar .ip").text(),
			online = $(".sidebar .ip").attr("data-online");

		if(name != "选择设备"){
			//设置弹窗
			$("#dialog-scout").dialog({
				resizable: false,
				width: 400,
				height: 380,
				modal: true,
				buttons: {
					"Save": function() {
						var dataParm = $("#scoutForm").serialize();
						//保存数据
						$.ajax({
							type: "POST",
							url: "/iec61850/setIedProperties",
							data: dataParm,
							success: function (d) {
								var item = d.data;
								if(d.success == true){
									$("#deviceList").prepend("<li><a href='javaScript:;' data-type='discover' data-ip='" + item.ip + "' data-path=''>" + item.ip + "</a></li>");
									$.gritter.add({
										title: 'success',
										text: '设置IED成功，在设备列表中选择对应设备！',
										position: 'bottom-right',
										class_name: 'gritter-success'
									});
									$("#dialog-scout").dialog("close");
								} else {
									$.gritter.add({
										title: 'error',
										text: d.msg,
										class_name: 'bottom-right'
									});
								}
							},
							error: function(error) {
								$.gritter.add({
									title: 'error',
									text: 'IEDScout data error！',
									class_name: 'bottom-right'
								});
							}
						});
					},
					"Cancel": function() {
						$(this).dialog("close");
					}
				}
			});
		} else {
			$.gritter.add({
				title: 'error',
				text: '在设备列表中选择对应设备！',
				class_name: 'bottom-right'
			});
		}

		//隐藏/显示
		toggleFn(tBtn, tLayer);

		//IP输入框
		$("#scoutForm .ip").ipaddress();

		//设置input属性
		disableBtnFn(disBtn, disInput_1, disInput_2);
	});

	//切换至浏览视图
	$(".topMenu .view-2").bind("click", function(){
		autoPageSize(2);
	});

	//切换至默认视图
	$(".topMenu .view-3").bind("click", function(){
		autoPageSize(3);
	});
}

//左侧栏“打开”事件
var iedsBtnFn = function () {
	var iedsBtn = $(".sidebar .iedsBtn"),
		iedList = $(".sidebar .iedList");

	//下拉按钮事件
	iedsBtn.bind("click", function(e){
		var iedsBtnW = $(".sidebar .iedsBtn").outerWidth();

		e.stopPropagation();
		//设置下拉框宽度
		iedList.css("width", iedsBtnW);
		iedList.removeClass("hide");
		iedList.animate({top: '102px'}, 100);
	});

	//关闭下拉框
	$(document).bind("click", function(){
		iedList.animate({top: '90px'}, 100);
		iedList.addClass("hide");
	});

	//选择对应值
	$(".sidebar .iedList").on("click", "ul li a", function(){
		var name = $(this).text(),
			ip = $(this).attr("data-ip"),
			type = $(this).attr("data-type"),
			path = $(this).attr("data-path"),
			online = $(this).attr("data-online"),
			port = $(this).attr("data-port");

		$(".sidebar .iedsBtn em").text(name);
		$(".sidebar .ip").text(ip);
		$(".sidebar .ip").attr("data-type", type);
		$(".sidebar .ip").attr("data-path", path);
		$(".sidebar .ip").attr("data-online", online);
		$(".sidebar .ip").attr("data-port", port);
		//do easyTreeAjax
		easyTreeAjax(ip, type, path);
	});
}

var dragBtnFn = function() {
	var clickX, leftOffset, inx, nextW2;
	var draging = false;
	var doc = document;
	var dragBtn = $(".mainLayer .dragBtn");
	var mainW = $(".mainLayer").width();
	var minWidth = 200;

	dragBtn.mousedown(function(){
		draging = true;
		leftOffset = $(".mainLayer").offset().left;
		inx = $(this).index(".dragBtn");
	});

	doc.onmousemove = function(e){
		if (draging) {
			clickX = e.pageX;
			nextW2 = clickX - leftOffset;

			//判断第几个拖动按钮
			if( inx == 0 ){
				if($(".mainLayer .item").is(":hidden")){
					//第一个拖动按钮
					if(clickX > minWidth && (mainW - clickX)  > minWidth) {
						dragBtn.eq(inx).parent().prev().width( clickX - leftOffset + 'px');
						dragBtn.eq(inx).parent().width( mainW - nextW2 + 'px');
					} else {
						draging = false;
					}
				} else {
					//第一个拖动按钮
					if(clickX > minWidth && clickX < (dragBtn.eq(inx+1).offset().left - minWidth)) {
						dragBtn.eq(inx).parent().prev().width( clickX - leftOffset + 'px');
						dragBtn.eq(inx).parent().width( (mainW - nextW2) / 2 + 'px');
						dragBtn.eq(inx).parent().next().width( (mainW - nextW2) / 2 + 'px');
					} else {
						draging = false;
					}
				}
				console.log("clickX:" + clickX);
				//console.log(dragBtn.eq(inx+1).offset().left - minWidth);
				console.log("eq(inx)Left:" + dragBtn.eq(inx).offset().left);
				console.log(mainW - clickX);
			}
			/*else {

			 //第二个拖动按钮左边不出界
			 if( (clickX) > dragBtn.eq(inx-1).offset().left + 10 ) {
			 dragBtn.eq(inx).css('left', clickX - 7 - leftOffset + 'px'); //按钮移动

			 dragBtn.eq(inx).prev().width( (clickX-leftOffset - dragBtn.eq(inx-1).prev().width()) + 'px');
			 nextW = clickX - leftOffset;
			 dragBtn.eq(inx).next().width( mainW - nextW  + 'px');
			 } else {
			 //第二个按钮向左移动不出界
			 dragBtn.eq(inx).css('left', parseFloat(dragBtn.eq(inx-1).css('left')) + 10 + 'px');

			 //第二个按钮左右容器，不出界
			 dragBtn.eq(inx).prev().width('0px')
			 dragBtn.eq(inx).next().width( mainW - dragBtn.eq(inx-1).prev().width() );
			 }

			 if( clickX >= (leftOffset + mainW) ) {
			 //第二个按钮右边不出界
			 dragBtn.eq(inx).css('left', mainW -10 + 'px'); //减去按钮的宽度
			 //第二个按钮左右容器，右边不出界
			 dragBtn.eq(inx).prev().width( mainW - dragBtn.eq(inx-1).prev().width());
			 dragBtn.eq(inx).next().width( '0px' );
			 }

			 }*/
		}
	}

	$(doc).mouseup(function(e) {
		draging = false;
		e.cancelBubble = true;
	});
}

//设备列表数据交互
var deviceListAjax = function (){
	$.ajax({
		type: "GET",
		url: "/iec61850/deviceLists",
		dataType: "json",
		success: function (d) {
			var item = d.data
			$("#deviceListTmpl").tmpl(item).appendTo("#deviceList");
		},
		error: function (error) {
			console.log('device data error!');
		}
	});
}

//树形菜单数据交互
var easyTreeAjax = function(ip, type, path) {
	$.ajax({
		type: "POST",
		url: "/iec61850/easyTree",
		data: {"ip": ip, "type": type, "path": path},
		dataType: "json",
		success: function(d) {
			var item = d.data;
			if(d.success == true) {
				var easyTree = $('#ET-demo').easytree({
					data: item.easyTreeJson
				});
			} else {
				$.gritter.add({
					title: 'error',
					text: d.msg,
					class_name: 'bottom-right'
				});
			}

			/*
			 //初始化全部节点展开
			 function openAllNodes() {
			 var nodes = easyTree.getAllNodes();
			 toggleNodes(nodes, 'open');
			 easyTree.rebuildTree(nodes);
			 }

			 //获取各节点
			 function toggleNodes(nodes, openOrClose){
			 for (var i = 0; i < nodes.length; i++) {
			 nodes[i].isExpanded = openOrClose == "open"; // either expand node or don't

			 // if has children open/close those as well
			 if (nodes[i].children && nodes[i].children.length > 0) {
			 toggleNodes(nodes[i].children, openOrClose);
			 }
			 }
			 }
			 */
			easyTreeClickFn(ip);
			//openAllNodes();
		},
		error: function(error){
			console.log('tree data error!');
		}
	});
}

//树形菜单各节点单击事件
var easyTreeClickFn = function(ip) {
	$(".sidebar .easyTree").find(".easytree-title").bind("click", function(){
		var nodeId = $(this).parent().attr("id");
		var disType = $(this).parent().attr("data-disType");
		var ip = $(".ip").text();
		var mainH = $(".mainLayer").height();

		//alert(ip);

		$(".treeList").css({"height": mainH - 26, "overflow-y": "auto"});

		if(disType == "list") {
			$.ajax({
				type: "POST",
				url: "/iec61850/table?disType=list&id=" + nodeId + "&ip=" + ip,
				dataType: "json",
				success: function (data) {
					$(".treeTable").hide();
					$(".treeList").show();
					$("#treeList").empty();
					if(data.length == 0){
						$("#treeList").html("<p>data is null.</p>");
					}
					$("#treeListTmpl").tmpl(data).appendTo("#treeList");
					$("#treeList li:even").addClass("bg");
				},
				error: function (error) {
					console.log('list data error!');
				}
			});
		} else if(disType == "fList"){
			$.ajax({
				type: "POST",
				url: "/iec61850/listFtpFiles",
				dataType: "json",
				success: function (data) {
					$(".treeList").hide();
					$(".treeTable").hide();
					$(".filesList").show();
					$("#filesList").empty();
					if(data.length == 0){
						$("#filesList").html("<p>data is null.</p>");
					}
					$("#filesListTmpl").tmpl(data).appendTo("#filesList");
				},
				error: function (error) {
					console.log('list data error!');
				}
			});
		} else {
			$(".treeList").hide();
			$(".treeTable").show();
			/*
			 * 替换当前url 并不导致浏览器页面刷新
			 * name 参数名
			 * value 参数值
			 */
			function replaceUrl  (name, value) {
				var obj = new Object();
				obj[name] = value;
				obj.rand = Math.random();
				History.replaceState(obj, '', '?' + name + '=' + value + "&ip=" + ip);
			}
			replaceUrl("easyTreeId", nodeId);
			$("#loadTreeTable").load("modules/treeTable.html");
		}
		//alert(nodeId)
	});
}

//关闭请求
var closeIEDAjax = function (ip, online){
	$.ajax({
		type: "POST",
		url: "/iec61850/closeIED",
		data: {"ip": ip, "online": online},
		dataType: "json",
		success: function (d) {
			if(d.success){
				//清空对应值
				$(".easyTree").empty();
				$("#loadTreeTable").empty();
				$(".filesList").empty();
				$(".sidebar .ip").empty();
				$("#deviceList").empty();
				$(".sidebar .iedsBtn em").text("选择设备");
				$(".sidebar .ip").text("- -");
				$(".sidebar .ip").attr("data-type", "");
				$(".sidebar .ip").attr("data-path", "");
				$(".sidebar .ip").attr("data-online", "");
				$(".sidebar .ip").attr("data-port", "");
				$.gritter.add({
					title: 'success',
					text: '设备已关闭！',
					class_name: 'bottom-right'
				});
				$("#dialog-text").dialog("close");
			} else {
				$.gritter.add({
					title: 'error',
					text: d.msg,
					class_name: 'bottom-right'
				});
			}
		},
		error: function(error) {
			$.gritter.add({
				title: 'error',
				text: 'closeIED data error！',
				class_name: 'bottom-right'
			});
		}
	});
}

//显示/隐藏
var toggleFn = function(btn, div) {
	btn.toggle(
		function () {
			div.hide();
		},
		function () {
			div.show();
		}
	);
}

//设置input属性
var disableBtnFn = function(btn, input1, input2) {
	if(!btn.attr('checked')){
		input1.next(".ip_container").find("input").attr("disabled", true);
		input2.attr("disabled", true);
	}

	//自定义input属性
	btn.bind("click", function() {
		if($(this).attr('checked')){
			input1.next(".ip_container").find("input").attr("disabled", false);
			input2.attr("disabled", false);
		}else{
			input1.next(".ip_container").find("input").attr("disabled", true);
			input2.attr("disabled", true);
		}
	});
}

$(function() {
	//页面初始化
	autoPageSize(3);
	topMenuFn();
	deviceListAjax();
	iedsBtnFn();
	dragBtnFn();
});